package com.hjzd.ai.smartpractice.websocket;

import com.hjzd.ai.smartpractice.config.WebClientConfig;
import com.hjzd.ai.smartpractice.service.RedisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.WebSocketSession;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * 会话管理器
 *
 * @author pengyonglei
 * @version 1.0.0
 */
public class SessionManager {
	private static final Logger logger = LoggerFactory.getLogger(SessionManager.class);

	public static final String FUNASR_CACHE = "funasrCache";
	public static final String AUDIO_STATUS_CACHE = "audioStatusCache";
	public static final String AUDIO_CACHE = "audioCache";
	public static final String ASR_CACHE = "asrCache";
	public static final String INTERFERE_CACHE = "interfereCache";
	public static final String SENTENCE_CACHE = "sentenceCache";
	public static final String TEMP_TEXT_CACHE = "tempTextCache";
	public static final String AUDIO_BYTES_CACHE = "audioBytesCache";
	public static final String BLOCKED_AUDIO_CACHE = "blockedAudioCache";
	public static final ConcurrentHashMap<WebSocketSession, byte[]> blockedAudioCache = new ConcurrentHashMap<>();


	// ws连接的缓存
	public static final ConcurrentHashMap<String, WebSocketSession> sessionCache = new ConcurrentHashMap<>();

	// ws连接的缓存
	public static final ConcurrentHashMap<WebSocketSession, AuthUserDTO> sessionInfoCache = new ConcurrentHashMap<>();

	// ws连接的缓存
	public static final ConcurrentHashMap<WebSocketSession, ConcurrentLinkedQueue<byte[]>> sessionOpenaiInfoCache = new ConcurrentHashMap<>();

	// web前端和java后端的ws连接 与 java后端和funasr服务的ws链接对象、 音频传输状态、的音频数据、转写结果、推理结果 的缓存
	public static final ConcurrentHashMap<WebSocketSession, ConcurrentHashMap<String, Object>> sessionPracticeCache = new ConcurrentHashMap<>();

//	// web前端和java后端的ws连接 与 java后端和funasr服务的ws链接对象 的缓存
//	public static final ConcurrentHashMap<WebSocketSession, FunasrWsClient> sessionFunasrCache = new ConcurrentHashMap<>();
//
//	// web前端和java后端的音频传输状态的缓存
//	public static final ConcurrentHashMap<WebSocketSession, String> sessionAudioStatusCache = new ConcurrentHashMap<>();
//
//	// web前端和java后端的音频缓存
//	public static final ConcurrentHashMap<WebSocketSession, byte[]> sessionAudioCache = new ConcurrentHashMap<>();
//
//	// web前端和java后端的转写缓存
//	public static final ConcurrentHashMap<WebSocketSession, StringBuilder> sessionAsrCache = new ConcurrentHashMap<>();

	// 用户消息通知ws链接的缓存
	public static final ConcurrentHashMap<String, WebSocketSession> userSessionCache = new ConcurrentHashMap<>();

	// 获取连接的会话
	public static WebSocketSession getSession(String key) {
		return sessionCache.get(key);
	}

	// 保存会话
	public static void saveSession(String key, WebSocketSession session) {
		sessionCache.put(key, session);
	}

	// 移除会话
	public static void removeSession(String key) {
		sessionCache.remove(key);
	}

	// 保存会话
	public static void saveSession(WebSocketSession session, AuthUserDTO authUserDTO) {
		sessionInfoCache.put(session, authUserDTO);
	}

	// 获取会话信息
	public static AuthUserDTO getSession(WebSocketSession session) {
		return sessionInfoCache.get(session);
	}

	// 获取会话用户信息
	public static AuthUserDTO getAuthUserDTOFromSession(WebSocketSession session) {
		return sessionInfoCache.get(session);
	}

	// 移除会话
	public static void removeSession(WebSocketSession session) {
		sessionInfoCache.remove(session);
	}

	// 保存会话
	public static void saveSessionOpenaiInfo(WebSocketSession session, ConcurrentLinkedQueue<byte[]> openaiInfo) {
		sessionOpenaiInfoCache.put(session, openaiInfo);
	}

	// 保存会话
	public static boolean sessionOpenaiInfoExist(WebSocketSession session) {
		return sessionOpenaiInfoCache.containsKey(session);
	}

	// 保存会话
	public static ConcurrentLinkedQueue<byte[]> getSessionOpenaiInfo(WebSocketSession session) {
		return sessionOpenaiInfoCache.get(session);
	}

	// 移除会话
	public static ConcurrentLinkedQueue<byte[]> removeSessionOpenaiInfo(WebSocketSession session) {
		return sessionOpenaiInfoCache.remove(session);
	}

	// 获取用户消息通知连接的会话
	public static WebSocketSession getUserSessionCache(String key) {
		return userSessionCache.get(key);
	}

	public static void removeUserSession(String key) {
		userSessionCache.remove(key);
	}

	// 保存用户消息通知会话
	public static void saveUserSession(String key, WebSocketSession session) {
		userSessionCache.put(key, session);
	}


	// 智能对练相关的会话缓存，初始化
	public static void initSessionPracticeCache(String aliyunAppKey, WebSocketSession session, RedisService redisService,
												WebClientConfig webClientConfig, String audioStatus, String ttsUrl, String saveVoicePath
			,String ttsType,String llmFlag,String llmUrl) throws URISyntaxException {
		// web前端和java后端的ws连接 与 java后端和funasr服务的ws链接对象 的缓存
		AliyunAsrClient aliyunAsrClient = new AliyunAsrClient(
				aliyunAppKey,
				session,
				redisService, webClientConfig, ttsUrl, saveVoicePath,ttsType,llmFlag,llmUrl
		);
		aliyunAsrClient.connect();
		//VolcanoAsrClient funasrCache = new VolcanoAsrClient(new URI(wsAddress), session, redisService, webClientConfig, ttsUrl, saveVoicePath,ttsType,llmFlag,llmUrl);
		// web前端和java后端的音频传输状态的缓存,audioStatus
		// web前端和java后端的音频缓存
		byte[] audioCache = new byte[0];
		// web前端和java后端的转写缓存
		StringBuilder asrCache = new StringBuilder();
		// web前端和java后端的转写缓存
		StringBuilder interfereCache = new StringBuilder();
		// web前端和java后端的推理结果分句缓存
		ConcurrentLinkedQueue<String> sentenceCache = new ConcurrentLinkedQueue<>();
		// web前端和java后端的推理结果分句用临时文本缓存
		String tempTextCache = "";
		// web前端和java后端的音频对话缓存
		List<Byte> audioBytesCache = new ArrayList<>();
		ConcurrentHashMap<String, Object> practiceCache = new ConcurrentHashMap<>();
		practiceCache.put("funasrCache", aliyunAsrClient);
		practiceCache.put("audioStatusCache", audioStatus);
		practiceCache.put("audioCache", audioCache);
		practiceCache.put("asrCache", asrCache);
		practiceCache.put("interfereCache", interfereCache);
		practiceCache.put("sentenceCache", sentenceCache);
		practiceCache.put("tempTextCache", tempTextCache);
		practiceCache.put("audioBytesCache", audioBytesCache);
		// 在会话缓存初始化中添加
		byte[] blockedAudioCache = new byte[0]; // 初始化为空
		practiceCache.put(BLOCKED_AUDIO_CACHE, blockedAudioCache);
		sessionPracticeCache.put(session, practiceCache);
	}

	// 智能对练相关的会话缓存，获取
	public static ConcurrentHashMap<String, Object> getPracticeCache(WebSocketSession session) {
		return sessionPracticeCache.get(session);
	}

	// 智能对练相关的会话缓存，获取
	public static ConcurrentHashMap<String, Object> clearSessionPracticeCache(WebSocketSession session) {
		return sessionPracticeCache.remove(session);
	}

	public static void updateClient(WebSocketSession session, VolcanoAsrClient newClient) {
		ConcurrentHashMap<String, Object> practiceCache = sessionPracticeCache.get(session);
		if (practiceCache != null) {
			practiceCache.put(FUNASR_CACHE, newClient);
			logger.info("已更新会话[{}]的ASR客户端实例", session.getId());
		} else {
			logger.warn("找不到会话[{}]的练习缓存", session.getId());
		}
	}

}
